﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Json;
using System.Reflection;

namespace TCPServer
{
    public class MyHttpClient
    {
        string _address = "http://localhost:83/test/AddLog";
        
        public MyHttpClient() { }
        public MyHttpClient(string uri)
        {
            _address = uri;
        }

        private LogDTO GetLog(byte[] bytes)
        {
            LogDTO log = new LogDTO();
            log.DeviceId = string.Format("{0:X2}-{1:X2}-{2:X2}-{3:X2}-{4:X2}-{5:X2}", bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5]);

            DateTime createDate1 = new DateTime(bytes[6] + 2000, bytes[7], bytes[8], bytes[9], bytes[10], bytes[11]);
            DateTime createDate2 = new DateTime(bytes[12] + 2000, bytes[13], bytes[14], bytes[15], bytes[16], bytes[17]);

            int vv = bytes[19];
            log.Voltage = vv;

            int si = bytes[21];
            log.SignalStrength = si;

            int count = bytes[23];

            int type = bytes[24];
            int water = BitConverter.ToInt16(new byte[] { bytes[27], bytes[26] }, 0);
            log.WaterLevel = water / 100;
            int type2 = bytes[28];
            int water2 = BitConverter.ToInt16(new byte[] { bytes[31], bytes[30] }, 0);
            //log.WaterLevel = water2 / 100;
            return log;
        }

        public void Post(byte[] bytes)
        {
            LogDTO log = GetLog(bytes);
            // Create an HttpClient instance 
            HttpClient client = new HttpClient();

            // Send a request asynchronously continue when complete 

            var content = new FormUrlEncodedContent(GetEntityToListKeyValuePair(log));

            client.PostAsync(_address, content);

            Console.WriteLine("Hit ENTER to exit...");
            Console.ReadLine();
        }
        private List<KeyValuePair<string, string>> GetEntityToListKeyValuePair(LogDTO log)
        {
            var keyvalus = new List<KeyValuePair<string, string>>();

            foreach (PropertyInfo po in
                log.GetType().GetProperties())
            {
                object rr = po.GetValue(log, null);

                if (rr != null && !string.IsNullOrWhiteSpace(rr.ToString()))
                {
                    // parse datatime and guid and bool type has some issue
                    if (!rr.ToString().Contains('/') && !rr.ToString().Contains('-') && !rr.ToString().Contains("False"))
                    {
                        keyvalus.Add(new KeyValuePair<string, string>(po.Name, rr.ToString()));
                        Console.WriteLine("{0}:  {1}", po.Name, rr);
                    }
                }
            }

            return keyvalus;
        }
    }
}
